//
//  NewNoteViewController.swift
//  Keyboard
//
//  Created by xinglian on 2022/12/20.
//

import UIKit
import TCCKit
class NewNoteViewController: BaseViewController {
    @IBOutlet var textField: UITextField!
    @IBOutlet var textView: UITextView!
    @IBOutlet var tips: UILabel!
    @IBOutlet var placeholder: UILabel!
    var model = NoteModel()
    var startModel = NoteModel()
    var array = [NoteModel]()
    var btnArray = [UIButton]()
    var index = 0
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        NotificationCenter.default.removeObserver(self)
        initUI()
    }
    
    override func initUI() {
        
        let rightItem = UIBarButtonItem(customView:self.rightBtn)
        var items = [rightItem]
        let icon = ["下一步","上一步"]
        let icon_select = ["下一步_选中","上一步_选中"]
        
        for i in 1...2{
            let btn = UIButton(type: .custom)
            btn.tag = 200 + 3 - i
            btn.setImage(UIImage(named:icon[i - 1]), for:.normal)
            btn.setImage(UIImage(named:icon_select[i - 1]), for:.selected)
            btn.addTarget(self, action:#selector(actionForBtn), for:.touchUpInside)
            let item = UIBarButtonItem(customView: btn)
            items.append(item)
            self.btnArray.append(btn)
        }
        self.navigationItem.rightBarButtonItems = items
        self.startModel = NoteModel.json(self.model)
        self.addModel()
        
        self.rightBtn.setTitle("", for: .normal)
        if self.traitCollection.userInterfaceStyle == .dark {
            // 暗黑模式
            self.textField.bgHexColor = "#000000"
            self.textView.bgHexColor = "#000000"
            self.tips.bgHexColor = "#000000"
            self.view.bgHexColor = "#000000"
            self.textField.textHexColor = "#FFFFFF"
            self.textView.textHexColor = "#FFFFFF"
            self.tips.textHexColor = "#FFFFFF"
            self.backBtn.setImage(UIImage(named:"返回"), for:.normal)
            self.rightBtn.setImage(UIImage(named:"完成_暗黑"), for: .normal)
        } else {
            self.textField.bgHexColor = "#FFFFFF"
            self.textView.bgHexColor = "#FFFFFF"
            self.tips.bgHexColor = "#FFFFFF"
            self.view.bgHexColor = "#FFFFFF"
            self.textField.textHexColor = "#000000"
            self.textView.textHexColor = "#000000"
            self.tips.textHexColor = "#000000"
            self.backBtn.setImage(UIImage(named:"返回_黑"), for:.normal)
            self.rightBtn.setImage(UIImage(named:"完成"), for: .normal)
        }
    }
    
    ///适配深色模式和浅色模式
    override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
        super.traitCollectionDidChange(previousTraitCollection)
        if self.traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) {
            // 根据当前主题更改UI元素
            self.initUI()
        }
    }
    
    func addModel(){
        let model = NoteModel.json(self.model)
        self.array.append(model)
        self.index = self.array.count - 1
        self.updateUI()
    }
    
    func updateUI(){
        let firstmodel = self.array.first!
        let lastmodel = self.array.last!
        let previousBtn = self.btnArray.last!
        let nextBtn = self.btnArray.first!
        nextBtn.isSelected = !(firstmodel.title == self.startModel.title && firstmodel.content == self.startModel.content)
        previousBtn.isSelected = !(lastmodel.title == self.startModel.title && lastmodel.content == self.startModel.content)
        
        self.tips.text = NSDate.transToDate("yyyy-MM-dd HH:mm:ss", "\(model.stamp as NSString)".intValue())
        self.textField.text = model.title
        self.textView.text = model.content
        self.placeholder.isHidden = model.content.count > 0
    }
    
    // 保存
    @objc override func rightBtnAction() {
        if self.model.stamp.count <= 0 {
            self.model.stamp = NSDate.currentTimeStamp("yyyy-MM-dd HH:mm:ss")
        }
        NoteTool.save(self.model) { success in
            NotificationCenter.default.post(name:updateNote, object: nil)
            self.backBtnAction()
        }
    }
    @objc func actionForBtn(sender:UIButton){
        if sender.tag == 201{///上一步
            self.model = self.index <= 0 ? self.array.first! : self.array[self.index-1]
            self.index = self.index == 0 ? 0 : self.index - 1
            self.updateUI()
        }else if sender.tag == 202{///下一步
            self.model = self.index >= self.array.count - 1 ? self.array.last! : self.array[self.index+1]
            self.index = self.index == self.array.count - 1 ? self.array.count - 1 : self.index + 1
            self.updateUI()
        }
    }
    
    
}
//MARK: - UITextField
extension NewNoteViewController:UITextFieldDelegate{
    func textFieldDidChangeSelection(_ textField: UITextField){
        if textField.markedTextRange == nil{
            self.model.title = textField.text ?? ""
            self.addModel()
        }
    }
}
//MARK: - UITextViewDelegate
extension NewNoteViewController:UITextViewDelegate{
    func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
        self.placeholder.isHidden = true
        return true
    }
    func textViewDidChange(_ textView: UITextView) {
        self.placeholder.isHidden = textView.text.count > 0
        if textView.markedTextRange == nil{
            self.model.content = textView.text
            self.addModel()
        }
    }
}
